package jnpf.database.sql.util;

import jnpf.database.sql.enums.base.SqlFrameBase;
import jnpf.util.text.CharsetKit;
import org.springframework.web.util.HtmlUtils;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 类功能
 *
 * @author JNPF开发平台组 YanYu
 * @version V3.2.0
 * @copyright 引迈信息技术有限公司
 * @date 2022/1/14
 */
public class SqlFrameUtil {

    /**
     * 去除模糊查询前后空白
     */
    public static String keyWordTrim(String keyWord){
        return keyWord.trim();
    }

    public static String htmlE(String str){
        if (str != null){
            return HtmlUtils.htmlEscape(str, CharsetKit.UTF_8);
        }
        return null;
    }

    private static final Pattern BRACKET = Pattern.compile("\\<.+?\\>");

    private static final Pattern BRACKET2 = Pattern.compile("\\[.+?\\]");

    /**
     * 正则处理
     */
    public static String formatSqlFrame(String sqlFrame){
        // 去除<param>的<>框架，<>：固定关键词，{}：参数，[]：可选关键词
        return sqlFrame.replace("<", "").replace(">", "")
                .replace("[", "").replace("]", "").replace("《schema》.", "");
    }

    /**
     * Sql框架参数设置
     * @param sqlFrameEnum SQL框架枚举
     * @param frameParamList 框架指定参数集合
     * @param params 实际参数集合
     * @return Sql语句
     */
    public static String outSqlCommon(SqlFrameBase sqlFrameEnum, List<String> frameParamList, String... params){
        String sqlFrame = sqlFrameEnum.getSqlFrame();
        List<String> paramList = Arrays.asList(params);
        sqlFrame = sqlFrameEnum.sqlSpecial(sqlFrame, frameParamList, paramList);
        // 对SQL框架指定参数进行赋值
        for (int i = 0; i < frameParamList.size(); i++) {
            sqlFrame = sqlFrame.replace(frameParamList.get(i), "?_" + i);
        }
        sqlFrame = SqlFrameUtil.formatSqlFrame(sqlFrame);
        for (int i = 0; i < paramList.size(); i++) {
            String param = paramList.get(i) != null ? paramList.get(i) : "";
            sqlFrame = sqlFrame.replace("?_" + i, param);
        }
        return sqlFrame;
    }

}
